//
//  PostViewController.m
//  AIM
//
//  Created by user10 on 2017/5/18.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "editViewController.h"
#import <Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "UIImage+Extension.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "NetWorkTools.h"
#import "DeviceInfo.h"
#import "DemoViewController.h"
#import "RecordAudio.h"
#import <UIImageView+WebCache.h>
#import "playVoiceViewController.h"

#define BIG_IMG_WIDTH  [UIScreen mainScreen].bounds.size.width
#define BIG_IMG_HEIGHT [UIScreen mainScreen].bounds.size.width * 16 / 9
@interface editViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextFieldDelegate,UIScrollViewDelegate,DemoViewControllerDelegate,UITextViewDelegate,AVPlayerViewControllerDelegate>{
    UIScrollView *background;
    UIImageView *imageView;
}

@property(nonatomic ,strong)UIScrollView *scrollV;
@property(nonatomic ,strong)UIButton *shareBtn;
@property(nonatomic ,strong)UILabel *titleL;
@property(nonatomic ,strong)UITextField *titleTextFiled;
@property(nonatomic ,strong)UILabel *productL;
@property(nonatomic ,strong)UITextField *productTextFiled;
@property(nonatomic ,strong)UIButton *fileBtn;
@property(nonatomic ,strong)UIButton *voiceBtn;
@property(nonatomic ,strong)UIButton *delBtn;
@property(nonatomic ,strong)UIImageView *image;
@property(nonatomic ,strong)NSString *dataString;
@property(nonatomic ,strong)NSString *dataType;
@property(nonatomic ,strong)NSString *dataName;
@property(nonatomic ,strong)RecordAudio *recordAudio;
@property(nonatomic ,strong)NSData *voiceData;
@property(nonatomic ,strong)UITextView *detailTextFiled;
@property(nonatomic ,strong)UILabel *placeholderL;
@property(nonatomic ,strong)NSString *videoUrl;
@property(nonatomic ,strong)AVPlayerViewController *avPlayer;

@property(nonatomic ,strong)NSString *MSG_DATA_TYPE;
@property(nonatomic ,strong)NSString *MSG_FILE;
@property(nonatomic ,strong)NSString *MSG_IMAGE;
@property(nonatomic ,strong)NSString *MSG_MEMO;
@property(nonatomic ,strong)NSString *MSG_TITLE;
@property(nonatomic ,strong)NSMutableArray *MSG_PRODUCTS;

@end


@implementation editViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    //导航栏中间的label
    UILabel *titleL = [[UILabel alloc]init];
    titleL.text = @"POST";
    titleL.textColor = [UIColor purpleColor];
    [titleL sizeToFit];
    self.navigationItem.titleView = titleL;
    //导航栏右侧按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 0, 30, 30);
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"post_cross"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(right) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
    [self loadData];
    //创建子控件
    [self createSubViews];
    //布局子控件
    [self layoutSubViews];
    _dataName =[NSString string];
    _dataType =[NSString string];
    _dataString =[NSString string];
    _productTextFiled.delegate = self;
    _recordAudio = [[RecordAudio alloc]init];
    
    _MSG_DATA_TYPE = [NSString string];
    _MSG_FILE = [NSString string];
    _MSG_IMAGE = [NSString string];
    _MSG_MEMO = [NSString string];
    _MSG_TITLE = [NSString string];
    _MSG_PRODUCTS = [NSMutableArray array];
    
}
//加载数据
- (void)loadData
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:getPostTextData>\
                                       <arg0>%@</arg0>\
                                       <arg1>%@</arg1>\
                                       </web:getPostTextData>",COMPANY,_messageId];
            
            NetWorkTools *tools = [NetWorkTools shareTools];
            
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostTextImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                NSRange startRange = [string rangeOfString:@"@@"];
                NSRange endRange = [string rangeOfString:@"</return>"];
                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                NSString *resultString = [string substringWithRange:range];
                
                NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                
                _MSG_DATA_TYPE = [getDict objectForKey:@"MSG_DATA_TYPE"];
                if ([_MSG_DATA_TYPE isEqualToString:@"IMAGE"]) {
                    _dataName = [self getNameBaseCurrentTime:@".jpg"];
                    _MSG_IMAGE = [getDict objectForKey:@"MSG_IMAGE"];
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_MSG_IMAGE]];
                    
                    NSString *base64String = [data base64EncodedStringWithOptions:0];
                    _dataString = base64String;
                    NSURL *imgURL = [NSURL URLWithString:_MSG_IMAGE];
                    [_image sd_setImageWithURL:imgURL];
                    _image.userInteractionEnabled = YES;
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapActions)];
                    [_image addGestureRecognizer:tapGesture];
                }else if ([_MSG_DATA_TYPE isEqualToString:@"VIDEO"]){
                    _dataName = [self getNameBaseCurrentTime:@".mov"];
                    _MSG_FILE = [getDict objectForKey:@"MSG_FILE"];
                    _MSG_IMAGE = [getDict objectForKey:@"MSG_IMAGE"];
                    _videoUrl = _MSG_FILE;
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_MSG_FILE]];
                    NSString *base64String = [data base64EncodedStringWithOptions:0];
                    _dataString = base64String;
                    NSURL *imgURL = [NSURL URLWithString:_MSG_IMAGE];
                    [_image sd_setImageWithURL:imgURL];
                    _image.userInteractionEnabled = YES;
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideos)];
                    [_image addGestureRecognizer:tapGesture];
                    
                }else if ([_MSG_DATA_TYPE isEqualToString:@"AUDIO"]){
                    _dataName = [self getNameBaseCurrentTime:@".mp3"];
                    _MSG_FILE = [getDict objectForKey:@"MSG_FILE"];
                    _MSG_IMAGE = [getDict objectForKey:@"MSG_IMAGE"];
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_MSG_FILE]];
                    NSString *base64String = [data base64EncodedStringWithOptions:0];
                    _dataString = base64String;
                    _image.image = [UIImage imageNamed:@"play_r6"];
                    _image.userInteractionEnabled = YES;
                    NSURL *voiceURL = [NSURL URLWithString:_MSG_FILE];
                    _voiceData = [NSData dataWithContentsOfURL:voiceURL];
                    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapVoice)];
                    [_image addGestureRecognizer:tapGesture];
                }else{
                    _delBtn.hidden = YES;
                }
                _detailTextFiled.text = [getDict objectForKey:@"MSG_MEMO"];
                if (_detailTextFiled.text.length != 0) {
                    _placeholderL.hidden =YES;
                }else{
                    _placeholderL.hidden =NO;
                }
                _titleTextFiled.text = [getDict objectForKey:@"MSG_TITLE"];
                _MSG_PRODUCTS = [getDict objectForKey:@"MSG_PRODUCTS"];
                if (_MSG_PRODUCTS.count != 0) {
                    _productTextFiled.text = _MSG_PRODUCTS[0];
                }
            }];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
}

//右侧关闭按钮
- (void)right{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillDisappear:animated];
}
- (void)createSubViews{
    UIScrollView *scrollV = [[UIScrollView alloc]init];
    scrollV.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    [self.view addSubview:scrollV];
    _scrollV = scrollV;
    
    //底部SHARE按钮
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setTitle:@"SHARE" forState:UIControlStateNormal];
    shareBtn.backgroundColor = [UIColor purpleColor];
    shareBtn.layer.cornerRadius = 5;
    shareBtn.titleLabel.textColor = [UIColor whiteColor];
    [shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareBtn];
    _shareBtn = shareBtn;
    
    //标题输入框
    UITextField *titleTextFiled = [[UITextField alloc]init];
    titleTextFiled.placeholder = @"Enter the title";
    titleTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    titleTextFiled.returnKeyType = UIReturnKeyDone;
    [scrollV addSubview:titleTextFiled];
    UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width,44)];
    
    UIBarButtonItem * button1 =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * button2 = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //定义完成按钮
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone  target:self action:@selector(finish)];
    
    //在toolBar上加上这些按钮
    NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
    [bar setItems:buttonsArray];
    titleTextFiled.inputAccessoryView = bar;
    _titleTextFiled = titleTextFiled;
    
    //详情输入框
    UITextView *detailTextFiled = [[UITextView alloc]init];
    detailTextFiled.delegate = self;
    detailTextFiled.layer.cornerRadius = 3;
    detailTextFiled.font = [UIFont systemFontOfSize:17];
    [scrollV addSubview:detailTextFiled];
    _detailTextFiled = detailTextFiled;
    _detailTextFiled.inputAccessoryView = bar;
    
    //TextView 占位Lable
    UILabel *placeholderL = [[UILabel alloc]init];
    placeholderL.text = @"Share your story here...";
    placeholderL.textAlignment = NSTextAlignmentLeft;
    placeholderL.textColor = [UIColor lightGrayColor];
    _placeholderL = placeholderL;
    [scrollV addSubview:_placeholderL];
    
    
    //productLabel
    UILabel * productL = [[UILabel alloc]init];
    productL.text = @"PRODUCT NO.";
    productL.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:productL];
    _productL = productL;
    
    //product 输入框
    UITextField *productTextFiled = [[UITextField alloc]init];
    productTextFiled.placeholder = @"Comma separated";
    productTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    productTextFiled.returnKeyType = UIReturnKeyDone;
    [scrollV addSubview:productTextFiled];
    productTextFiled.inputAccessoryView = bar;
    _productTextFiled = productTextFiled;
    
    //文件选择按钮
    UIButton *fileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [fileBtn setTitle:@"File" forState:UIControlStateNormal];
    fileBtn.backgroundColor = [UIColor blueColor];
    fileBtn.layer.cornerRadius = 5;
    [scrollV addSubview:fileBtn];
    [fileBtn addTarget:self action:@selector(alert) forControlEvents:UIControlEventTouchUpInside];
    _fileBtn = fileBtn;
    
    
    //语音按钮
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setBackgroundImage:[UIImage imageNamed:@"postcomment_menu_voice"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(clickVoice) forControlEvents:UIControlEventTouchUpInside];
    [scrollV addSubview:voiceBtn];
    _voiceBtn = voiceBtn;
    
    //图片
    UIImageView *image = [[UIImageView alloc]init];
    [scrollV addSubview:image];
//    image.image = NULL;
    _image = image;
    
    //语音按钮
    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setBackgroundImage:[UIImage imageNamed:@"post_cross"] forState:UIControlStateNormal];
    [scrollV addSubview:delBtn];
    delBtn.hidden = NO;
    [delBtn addTarget:self action:@selector(del) forControlEvents:UIControlEventTouchUpInside];
    _delBtn = delBtn;
    
    
}
- (void)finish{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
- (void)clickVoice{
    DemoViewController *voiceVc = [[DemoViewController alloc]init];
    voiceVc.delegate = self;
    voiceVc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    voiceVc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:voiceVc animated:YES completion:nil];
}

- (void)preparePost:(NSData *)data{
    _delBtn.hidden = NO;
    [_image setImage:[UIImage imageNamed:@"play_l6"]];
    _dataType = @"AUDIO";
    _voiceData = data;
    _MSG_DATA_TYPE = @"AUDIO";
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    _dataString = base64String;
    _dataName = [self getNameBaseCurrentTime:@".mp3"];
    _image.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapVoice)];
    [_image addGestureRecognizer:tapGesture];
}

//播放音频
- (void)tapVoice{
//    NSLog(@"voice-----");
//    [_recordAudio.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//    
//    [_recordAudio.audioSession setActive:YES error: nil];
//    [_recordAudio play:_voiceData];
    
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"bundle:nil];
    playVoiceViewController *voiceVc = [mainStoryboard instantiateViewControllerWithIdentifier:@"playVoiceViewController"];
    voiceVc.voiceData = _voiceData;
    [self presentViewController:voiceVc animated:YES completion:nil];
}

- (void)layoutSubViews {
    //scrollView布局
    [_scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat height = [UIScreen mainScreen].bounds.size.height - 50;
        //尺寸约束
        make.size.mas_equalTo(CGSizeMake([UIScreen mainScreen].bounds.size.width, height));
        //位置约束
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.top.mas_equalTo(self.view.mas_top).offset(5);
    }];
    //分享按钮布局
    [_shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(90,44));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(_scrollV.mas_bottom);
    }];
    //title输入框布局
    [_titleTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_scrollV.mas_left).offset(5);
        make.top.mas_equalTo(_scrollV.mas_top).offset(0);
    }];
    //详情输入框布局
    [_detailTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(260);
        make.left.mas_equalTo(_titleTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_titleTextFiled.mas_bottom).offset(5);
    }];
    //占位label布局
    [_placeholderL mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(35);
        make.left.mas_equalTo(_detailTextFiled.mas_left).offset(5);
        make.top.mas_equalTo(_detailTextFiled.mas_top).offset(0);
    }];
    //lable布局
    [_productL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_detailTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_detailTextFiled.mas_bottom).offset(5);
    }];
    //productNo布局
    [_productTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 10;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_productL.mas_left).offset(0);
        make.top.mas_equalTo(_productL.mas_bottom).offset(5);
    }];
    //文件选择按钮布局
    [_fileBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width * 0.25;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_productTextFiled.mas_left).offset(0);
        make.top.mas_equalTo(_productTextFiled.mas_bottom).offset(5);
    }];
    //录音按钮布局
    [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(30);
        make.right.mas_equalTo(_productTextFiled.mas_right);
        make.top.mas_equalTo(_fileBtn.mas_top);
    }];
    //图片位置的布局
    [_image mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width * 0.33;
        CGFloat height = width * 4 / 3;
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(height);
        make.top.mas_equalTo(_fileBtn.mas_bottom).offset(5);
        make.centerX.mas_equalTo(_scrollV.mas_centerX);
    }];
    
    //删除按钮布局
    [_delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(_image.mas_right).offset(5);
        make.top.mas_equalTo(_image.mas_top);
    }];
    
    _scrollV.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 650);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (![text isEqualToString:@""]) {
        _placeholderL.hidden = YES;
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        _placeholderL.hidden = NO;
    }
    
    return YES;
}

- (void)alert{
    
    
    //alert弹层
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    //照片库
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"Photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"照片库");
        UIImagePickerController *pick=[[UIImagePickerController alloc]init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            pick.allowsEditing=true;
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相册不可用");
        }
        
        
    }];
    
    //视频库
    UIAlertAction *video = [UIAlertAction actionWithTitle:@"Video" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"视频库");
        UIImagePickerController *pick=[[UIImagePickerController alloc]init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            pick.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
            pick.allowsEditing=true;
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相册不可用");
        }
    }];
    //拍摄照片
    UIAlertAction *takephoto  = [UIAlertAction actionWithTitle:@"Take a picture" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController *pick=[[UIImagePickerController alloc]init];
            pick.sourceType=UIImagePickerControllerSourceTypeCamera;//设置 pick 的类型为相机
            pick.allowsEditing=true;//设置是否可以编辑相片涂鸦
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相机不可用");
        }
        NSLog(@"拍摄照片");
    }];
    //拍摄视频
    UIAlertAction *takeVideo  = [UIAlertAction actionWithTitle:@"Shoot a video" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"拍摄视频");
        _dataName = [self getNameBaseCurrentTime:@"mov"];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSArray * mediaTypes =[UIImagePickerController  availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            UIImagePickerController *pick=[[UIImagePickerController alloc]init];
            pick.sourceType = UIImagePickerControllerSourceTypeCamera;//设置 pick 的类型为相机
            pick.mediaTypes = @[mediaTypes[1]];
            pick.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            pick.allowsEditing=true;//设置是否可以编辑相片涂鸦
            pick.delegate=self;
            [self presentViewController:pick animated:true completion:nil];
        }
        else
        {
            NSLog(@"相机不可用");
        }
        NSLog(@"拍摄照片");
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:photo];
    [alertController addAction:video];
    [alertController addAction:takephoto];
    [alertController addAction:takeVideo];
    
    if([DeviceInfo deviceIsPhone]){
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        UIPopoverPresentationController *popPresenter = [alertController
                                                         popoverPresentationController];
        popPresenter.sourceView = _fileBtn; // 这就是挂靠的对象
        popPresenter.sourceRect = _fileBtn.bounds;
        popPresenter.permittedArrowDirections = UIPopoverArrowDirectionDown;
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
- (void)del{
    _image.image = nil;
    _delBtn.hidden = YES;
    
    _dataString = @"";
    _dataName = @"";
    _MSG_DATA_TYPE = @"TEXT";
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type=[info objectForKey:UIImagePickerControllerMediaType];
    
    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    // define the block to call when we get the asset based on the url (below)
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
    {
        if ([type isEqualToString:@"public.image"])
        {
            _dataName = [self getNameBaseCurrentTime:@"img"];
            
        }else{
            
            ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
            _dataName = [imageRep filename];
            if (_dataName == nil) {
                _dataName = [self getNameBaseCurrentTime:@".mov"];
            }
        }
    };
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    
    //判断选择的是否是图片,这个 public.image和public.movie是固定的字段.
    if ([type isEqualToString:@"public.image"])
    {
        //设置dataType类型
        _MSG_DATA_TYPE = @"IMAGE";
        
        //其实这样就已经实现了设置图片的功能
        UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
        }
        //        NSData *imageData = UIImagePNGRepresentation(image);
        NSData *imageData = [UIImage compressWithOrgImg:image];
        NSString *base64String = [imageData base64EncodedStringWithOptions:0];
        _dataString = base64String;
        [_image setImage:image];
        //允许用户交互
        _image.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapActions)];
        [_image addGestureRecognizer:tapGesture];
        if (_image.image != nil) {
            _delBtn.hidden = NO;
        }
    }
    //判断选择的是否是视频
    if ([type isEqualToString:@"public.movie"]) {
        //如果是视频资源
        NSURL *sourceURL = info[UIImagePickerControllerMediaURL];
        //        [self compressVideo:sourceURL];
        _videoUrl = [sourceURL absoluteString];
        NSData *data = [NSData dataWithContentsOfURL:sourceURL];
        
        NSString *base64String = [data base64EncodedStringWithOptions:0];
        
        _dataName = [self getNameBaseCurrentTime:@".mov"];
        _MSG_DATA_TYPE = @"VIDEO";
        _dataString = base64String;
        _image.image = [self thumbnailImageForVideo:sourceURL atTime:1];
        //允许用户交互
        _image.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideos)];
        [_image addGestureRecognizer:tapGesture];
        if (_image.image != nil) {
            _delBtn.hidden = NO;
        }
        //        self.videoUrl = sourceURL;
        //        NSURL *newVideoUrl ; //一般.mp4
        NSLog(@"%@",sourceURL);
        
        [picker dismissViewControllerAnimated:YES completion:^{}];
    }
    [picker dismissViewControllerAnimated:false completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"取消");
    [picker dismissViewControllerAnimated:false completion:nil];
}
//播放视频
- (void)playVideos
{
    NSString *url = _videoUrl;
    NSURL * videoURL = [NSURL URLWithString:url];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"error = %@",[error description]);
    }
    
    _avPlayer = [[AVPlayerViewController alloc] init];
    //    _avPlayer.player = [[AVPlayer alloc] initWithURL:videoURL];
    _avPlayer.delegate = self;
    _avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    _avPlayer.player = player;
    [self presentViewController:_avPlayer animated:YES completion:^{
        [_avPlayer.player play];
    }];
    
    
//    NSString *url = _videoUrl;
//    
//    NSURL * videoURL = [NSURL URLWithString:url];
//    _avPlayer = [[AVPlayerViewController alloc] init];
//    _avPlayer.player = [[AVPlayer alloc] initWithURL:videoURL];
//    
//    /*
//     可以设置的值及意义如下：
//     AVLayerVideoGravityResizeAspect   不进行比例缩放 以宽高中长的一边充满为基准
//     AVLayerVideoGravityResizeAspectFill 不进行比例缩放 以宽高中短的一边充满为基准
//     AVLayerVideoGravityResize     进行缩放充满屏幕
//     */
////    _avPlayer.allowsPictureInPicturePlayback = NO;
//    _avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
//    //自动播放
//    [_avPlayer.player play];
//    [self presentViewController:_avPlayer animated:YES completion:nil];
}
//视频播放的代理
- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController
{
    //表示最小化后，dismiss掉原来视图的的layer
    return YES;
}

- (void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler
{
    //恢复原来的视图 重新present
    [self presentViewController:playerViewController animated:YES completion:^{
        completionHandler(YES);
    }];
}

//点击图片后的方法
- (void)tapActions{
    //创建一个黑色背景
    //初始化一个用来当做背景的View。
    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    background = bgView;
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [self.view addSubview:bgView];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH, [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_image.image];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    } else {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView setImage:_image.image];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake(BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=2.0;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    }
    
    
    
}
//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

-(void)closeView{
    [background removeFromSuperview];
}
//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

- (void)share{
    
    NSUserDefaults *user  = [NSUserDefaults standardUserDefaults];
    NSString *userStr = [user objectForKey:@"TANTO_CD"];
    
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    
    
    [dict setObject:userStr forKey:@"SHARE_TANTO"];
    [dict setObject:COMPANY forKey:@"SHARE_COMPANY_CD"];
    [dict setObject:_messageId forKey:@"SHARE_MESSAGE_ID"];
    [dict setObject:_titleTextFiled.text forKey:@"SHARE_TEXT_TITLE"];
    [dict setObject:_detailTextFiled.text forKey:@"SHARE_TEXT_MEMO"];
    [dict setObject:_productTextFiled.text forKey:@"SHARE_TEXT_PRODUCT_NO"];
    [dict setObject:_dataString forKey:@"SHARE_TEXT_BIN_DATA"];
    [dict setObject:_dataName forKey:@"SHARE_TEXT_FILE_NAME"];
    [dict setObject:_MSG_DATA_TYPE forKey:@"SHARE_TEXT_STYLE"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *tempStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            
        
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:updatePostTextData>\
                                       <arg0>%@</arg0>\
                                       </web:updatePostTextData>",tempStr];
            //初始化网络工具类
            NetWorkTools *tools = [NetWorkTools shareTools];
            //发送网络请求
        
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostTextImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                NSRange startRange = [string rangeOfString:@"<return>"];
                NSRange endRange = [string rangeOfString:@"</return>"];
                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                NSString *resultString = [string substringWithRange:range];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
}
- (void)delLast{
    
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<web:deletePostDetailData>\
                               <arg0>%@</arg0>\
                               <arg1>%@</arg1>\
                               </web:deletePostDetailData>",COMPANY,_messageId];
    
    NetWorkTools *tools = [NetWorkTools shareTools];
    
    [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostDetailImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
//视频相关
- (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}

#pragma mark -------textField代理-------
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self share];
    return YES;
}

#pragma mark ————————— 以当前时间合成视频名称 —————————————
- (NSString *)getNameBaseCurrentTime:(NSString *)type{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:type];
}




@end
